package 预科0104ChattingRoom_Q5;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;


public class Clientlistener implements Runnable{

    private Socket socket;
    private String name;
    public static  String msg = null;
    public Clientlistener(Socket socket ,String name) {
        this.socket = socket;
        this.name = name;
    }

    BufferedReader bufferedReader = null;
        @Override

        public void run() {

            try {
                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;

                while (true){
                    msg = bufferedReader.readLine();
                    if(null == msg){
                        break;
                    }
                    else if("file".equalsIgnoreCase(msg)){
                        String filename = bufferedReader.readLine();
                        if("fail".equalsIgnoreCase(filename)){
                            System.out.println("下载失败！");
                        }else {
                            bis = new BufferedInputStream(socket.getInputStream());
                            bos = new BufferedOutputStream(new FileOutputStream(ServerTest.lockfilename +
                                    name + "/" + filename));
                            byte[] bytes = new byte[1024];
                            int res = 0;
                            while ((res = bis.read(bytes)) != -1){
                                bos.write(bytes,0,res);
                                bos.flush();
                                if(res < 1024){
                                    break;
                                }
                            }
                            System.out.println("已保存到本地！");
                        }
                    }
                    else {
                        System.out.println(msg);
                    }

                }
            }
            catch (SocketException e){
                System.out.println("关闭 Socket:" + e.getMessage());

            }
            catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(null!=bufferedReader){
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

        }
    }
}
